package net.flyinggroup.mutation.controller;

import net.flyinggroup.mutation.model.Book;
import net.flyinggroup.mutation.model.BookInput;
import net.flyinggroup.mutation.repository.BookRepository;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookRepository bookRepository;

    public BookController(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    @QueryMapping
    public List<Book> allBooks() {
        return bookRepository.findAll();
    }

    @MutationMapping
    public Book createBook(@Argument String title, @Argument Integer pages, @Argument String author) {
        Book book = new Book();
        book.setTitle(title);
        book.setPages(pages);
        book.setAuthor(author);
        return bookRepository.save(book);
    }

    @MutationMapping
    public Book addBook(@Argument BookInput book) {
        Book newBook = new Book();
        newBook.setTitle(book.getTitle());
        newBook.setPages(book.getPages());
        newBook.setAuthor(book.getAuthor());
        return bookRepository.save(newBook);
    }

    @MutationMapping
    public List<Book> batchCreate(@Argument List<BookInput> books) {
        return bookRepository.saveAll(books.stream().map(bookInput -> {
            Book newBook = new Book();
            newBook.setTitle(bookInput.getTitle());
            newBook.setPages(bookInput.getPages());
            newBook.setAuthor(bookInput.getAuthor());
            return newBook;
        }).toList());
    }
}
